<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Manga extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('manga_model');
        $this->load->library('upload');
    }

    /**
     * Controller to list all manga page
     */
    public function index() {
        $data = $this->manga_model->getManga_all();
        $this->load->view('manga/all', array('manga' => $data));
    }

    /**
     * Controller to add manga page
     */
    public function add() {
        $this->load->view('manga/add');
    }

    /**
     * Controller to edit manga page
     */
    public function edit($mid = 0) {
        if ($mid == 0) {
            show_404();
            die();
        }
        $manga = $this->manga_model->getManga_by_id($mid);
        if ($manga)
            $this->load->view('manga/edit', array('manga' => $manga));
        else
            show_404();
    }

    /**
     * Ajax add new manga
     */
    public function ajax_add_new_manga() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        $arr = $this->manga_model->addManga_validate($_POST);
        if ($arr['err'] == 0) {
            extract($_POST);
            $status = !isset($staus) ? 1 : $status;
            $data = array(
                'name' => trim($name),
                'description' => trim($desc),
                'author' => trim($author),
                'translator' => trim($translator),
                'oname' => trim($oname),
                'cover' => trim($cover),
                'status' => $status
            );
            $arr['err'] = $this->manga_model->addManga($data) ? 0 : -1;
        }
        echo json_encode($arr);
    }

    /**
     * Ajax upload cover
     */
    public function ajax_upload_manga_cover() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }
        $result = $this->manga_model->uploadCover();

        $data = array();
        $data['err'] = $result['err'];
        $data['msg'] = $result['msg'];
        $relative = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', "", $result['data']['full_path']);
        $data['furl'] = base_url() . $relative;
        $data['cover_path'] = $relative;

        echo json_encode($data);
    }

    /**
     * Ajax save edit manga
     */
    public function ajax_edit_manga() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }
        $arr = $this->manga_model->addManga_validate($_POST);
        if ($arr['err'] == 0) {
            extract($_POST);
            $role = !isset($role) ? 1 : $role;

            $data = array(
                'id' => $id,
                'name' => trim($name),
                'slug' => slug($name),
                'description' => trim($desc),
                'author' => trim($author),
                'translator' => trim($translator),
                'oname' => trim($oname),
                'cover' => trim($cover),
                'status' => $status
            );
            $arr['err'] = $this->manga_model->editManga($data) ? 0 : -1;
            $arr['slug'] = slug($name);
        }
        echo json_encode($arr);
    }

    /*
     * Ajax to remove a manga
     */
    function ajax_remove_manga() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['id'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing parameter.'));
            die;
        }

        $id = $_POST['id'];
        $rm = $this->manga_model->removeManga($id);
        if ($rm)
            echo json_encode(array('err' => 0, 'msg' => 'Successfull.'));
        else
            echo json_encode(array('err' => -1, 'msg' => 'Something wrong...'));
    }

    /**
     * Controller to create new chapter
     */
    function ajax_add_new_chapter() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['mangaId']) || !isset($_POST['chapterId'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing parameter.'));
            die;
        }

        extract($_POST);
        $arr = array();
        if (!is_numeric($mangaId) || !is_numeric($chapterId)) {
            $arr['err'] = -1;
            $arr['msg'] = 'Invalid parameter.';
        } else if (count($this->manga_model->getChapter_by_chapterId($mangaId, $chapterId)) > 0) {
            $arr['err'] = -1;
            $arr['msg'] = 'Chapter exist.';
        } else {
            $arr['err'] = $this->manga_model->addNewChapter($mangaId, $chapterId) ? 0 : -1;
        }
        echo json_encode($arr);
    }
    
    /**
     * Ajax to edit a chapter
     */
    function ajax_edit_chapter() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }
    }
    
    /**
     * Ajax to remove a chapter
     */
    function ajax_remove_chapter() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }
    }
    
    /**
     * Ajax to upload images to a chapter folder 
     * This just for review images list
     */
    function ajax_upload_chapter_image() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        extract($_POST);
        if (!isset($_POST['mangaId']) || !isset($_POST['chapterId']) || $_POST['chapterId'] == '') {
            echo json_encode(array('err' => -1, 'msg' => 'Missing Parameter'));
            die();
        }
        $slug = !isset($_POST['slug']) ? $this->manga_model->getManga_slug_by_id($mangaId) : $_POST['slug'];
        $result = $this->manga_model->uploadChapterImage($slug, $chapterId);

        $data = array();
        $data['err'] = $result['err'];
        $data['msg'] = $result['msg'];
        $relative = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', "", $result['data']['full_path']);
        $data['furl'] = base_url() . $relative;
        $data['image_path'] = $relative;

        echo json_encode($data);
    }
    
    /**
     * Ajax to remove an images out of a chapter
     * This will also remove the image file
     */
    function ajax_remove_chapter_image() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }
    }

    /**
     * Ajax to save images to a chapter
     * This will serialize the images list and update to chapter
     */
    function ajax_add_chapter_image() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        extract($_POST);
        $images = isset($images) ? $images : '';
        $data = array('mangaId' => $mangaId, 'chapterId' => $chapterId, 'images' => serialize($images));
        $arr['err'] = $this->manga_model->updateChapter_by_chapterId($data) ? 0 : -1;
        echo json_encode($arr);
    }

    /**
     * Ajax to get images of a chapter
     */
    function ajax_get_chapter_image() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        $arr = $this->manga_model->getChapter_validate($_POST);
        if ($arr['err'] == 0) {
            extract($_POST);
            $data = $this->manga_model->getChapter_by_chapterId($mangaId, $chapterId);
            $data['images'] = unserialize($data['images']);
            $arr['data'] = $data;
        }
        echo json_encode($arr);
    }

    /**
     * Ajax to get an image from an image link
     */
    function ajax_get_image_single_link() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['url']) || !isset($_POST['mangaId']) || !isset($_POST['chapterId'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing Parameter'));
            die();
        }
        extract($_POST);
        $slug = !isset($_POST['slug']) ? $this->manga_model->getManga_slug_by_id($mangaId) : $_POST['slug'];

        $result = $this->manga_model->getImage_by_single_link($url, $slug, $chapterId);
        $data['err'] = count($result) ? 0 : -1;
        $data['msg'] = count($result) ? 'Success.' : 'Upload Failure.';
        $data['listImg'] = $result;
        echo json_encode($data);
    }

    /**
     * Ajax to get images from an array of images
     */
    function ajax_get_image_multi_link() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['data']) || !isset($_POST['mangaId']) || !isset($_POST['chapterId'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing Parameter'));
            die();
        }
        extract($_POST);
        $slug = !isset($_POST['slug']) ? $this->manga_model->getManga_slug_by_id($mangaId) : $_POST['slug'];

        $result = $this->manga_model->getImage_by_multi_link($data, $slug, $chapterId, $mangaId);
        $arr['err'] = count($result) > 0 ? 0 : -1;
        $arr['msg'] = count($result) > 0 ? 'Success.' : 'Upload Failure.';
        $arr['listImg'] = $result;
        echo json_encode($arr);
    }
    
    /**
     * Ajax to Parse a chapter of a manga 
     */
    function ajax_getManga_chapter_by_link() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['url']) || !isset($_POST['from']) || !isset($_POST['mangaId'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing parameter.'));
            die;
        }

        extract($_POST);
        switch ($from) {
            case 0:
                $result = $this->manga_model->parseLink_truyentranhtuan($url);
                $data['ifurl'] = base_url() . 'tmp/manga_truyentranhtuan.html';
                break;
        }
        $data['err'] = $result ? 0 : -1;
        $data['msg'] = $result ? 'Get HTML Success' : 'Get HTML Failure';
        echo json_encode($data);
    }

    /**
     * Ajax to Parse and get chapter link
     */
    function ajax_get_chapter_link_content() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['url'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing Parameter'));
            die();
        }

        extract($_POST);
        $cb = isset($cb) ? $cb : '';
        $chapterId = isset($chapterId) ? $chapterId : 0;
        switch ($from) {
            case 0:
                $path = $this->manga_model->parseLinkContent_truyentranhtuan($url, $chapterId, $cb);
                $data['ifurl'] = $path;
                break;
        }
        $data['err'] = $path ? 0 : -1;
        $data['msg'] = $path ? 'Get HTML Success' : 'Get HTML Failure';
        echo json_encode($data);
    }

    /**
     * Ajax to remove all chapter
     */
    function ajax_remove_all_chapter() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['mangaId']) || !isset($_POST['chapterId'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing Parameter'));
            die();
        }
        extract($_POST);
        $slug = !isset($_POST['slug']) ? $this->manga_model->getManga_slug_by_id($mangaId) : $_POST['slug'];
        $this->manga_model->removeChapter_image_file($slug, $chapterId);
        echo json_encode(array('err' => 0, 'msg' => ''));
    }

    /**
     * Ajax to delete a chapter
     */
    function ajax_delete_chapter() {
        if (!check_action_role(__FUNCTION__)) {
            echo json_encode(array('err' => -1, 'msg' => 'Permission Denied'));
            die();
        }

        if (!isset($_POST['mangaId']) || !isset($_POST['chapterId'])) {
            echo json_encode(array('err' => -1, 'msg' => 'Missing Parameter'));
            die();
        }
        extract($_POST);
        $slug = !isset($_POST['slug']) ? $this->manga_model->getManga_slug_by_id($mangaId) : $_POST['slug'];
        $this->manga_model->deleteChapter_by_id($slug, $chapterId, $mangaId);
        echo json_encode(array('err' => 0, 'msg' => ''));
    }

}
